# -*- coding: UTF-8 -*-     
import tornado.ioloop
import tornado.web
import random

import redis
import lib.api as API
import json

r = redis.Redis(host='127.0.0.1', port=6379, db=0)

class CrossDomain:
    def __init__(self):
        pass

    def write(self, str):
        self.set_header("Content-Type","application/json")
        self.set_header("Access-Control-Allow-Origin","*")
        self.set_header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS")
        self.set_header("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
        self.write(str)

class MainHandler(tornado.web.RequestHandler, CrossDomain):
    def get(self):
        CrossDomain.write(self, r'hey man!')

class GetNewMoviesHandler(tornado.web.RequestHandler, CrossDomain):
    def get(self):
        if r.get('new_movie') != None:
            pageNum = int(self.get_argument('pageNum'))
            pageSize = int(self.get_argument('pageSize'))
            first_pos = pageNum*pageSize
            last_pos = first_pos + pageSize
            json_str = r.get('new_movie').decode()
            data = json.loads( json_str )
            #print(data);
            #CrossDomain.write(self, pageNum + "/" + pageSize )
            CrossDomain.write(self, json.dumps(data[first_pos:last_pos]) )
        else:
            CrossDomain.write(self, json.dumps({'code': 1, 'msg': 'error'}))

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/get_new_movies", GetNewMoviesHandler)
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(3000)
    tornado.ioloop.IOLoop.current().start()



